<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function index()
    {
        return view('login.login');
    }

    /**
     * Handle an incoming authentication request.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function doLogin(Request $request)
    {
        $username = $request->input('username', '');
        $password = $request->input('password', '');
        try {
            //查询账号
            $admin = (array)DB::table('admin_users')
                ->where([
                    'username' => $username,
                ])->first();
            if (empty($admin)) {
                throw new \Exception("账号不正确");
            }
            if (md5($password) != $admin['password_m']) {
                throw new \Exception("密码不正确");
            }
            $request->session()->put('username', $admin['username']);
            $request->session()->put('admin_id', $admin['id']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success([
//            'url' => $retUrl
        ]);

    }

    /**
     * Destroy an authenticated session.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    {
        $request->session()->flush(); //清空所有
//        删除键
//        session()->forget('key3');
//        根据键删除数据同时返回
//$request->session()->pull('key3');
        return redirect('/isLogin');
    }
}
